//
//  UIAlertController+Category.swift
//  HighScoreTalk
//
//  Created by Apple on 16/2/16.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit
extension UIAlertController {
    convenience init(title:String,message:String,cancelTitle:String,otherTitles:[String],context:UIViewController,complete:(UIAlertController,Int)->Void) {
        self.init(title:title, message: message, preferredStyle: .Alert)
        let shouldCancel = (cancelTitle.characters.count > 0)
        for i in  0..<otherTitles.count {
            let t = otherTitles[i]
            self.addAction(UIAlertAction(title: t, style: .Default, handler: { (action) -> Void in
                var index = 0
                if action.title == cancelTitle {
                    complete(self,0)
                } else {
                    for i in 0..<otherTitles.count{
                        if action.title == otherTitles[i] {
                            index = i
                        }
                    }
                    if shouldCancel {
                        complete(self,index+1)
                    } else {
                        complete(self,index)
                    }
                }
            }))
        }
        
        if shouldCancel {
            self.addAction(UIAlertAction(title: cancelTitle, style: .Cancel, handler: { (action) -> Void in
                complete(self,0)
            }))
        }
        context.presentViewController(self, animated: true, completion: nil)
    }
    convenience init(title:String,message:String,cancelTitle:String,context:UIViewController,complete:(UIAlertController,Int)->Void){
        self.init(title:title,message:message,cancelTitle:cancelTitle,otherTitles:[],context: context,complete:complete)
        
    }
    
    convenience init(title:String,message:String,cancelTitle:String,context:UIViewController){
        self.init(title:title,message:message,cancelTitle:cancelTitle,otherTitles:[],context: context,complete:{(context) in })
    }
    
    convenience init(title:String,message:String,context:UIViewController){
        self.init(title:title,message:message,cancelTitle:"确定",otherTitles:[],context: context,complete:{(context) in })
    }
    
    convenience init(title:String,context:UIViewController){
        self.init(title:title,message:"",cancelTitle:"确定",otherTitles:[],context: context,complete:{(context) in })
    }
    
    convenience init(message:String,context:UIViewController){
        self.init(title:"",message:message,cancelTitle:"确定",otherTitles:[],context: context,complete:{(context) in })
    }
    
    
    func dismiss(time:Int64,complete:()->Void) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, time), dispatch_get_main_queue(), {
            self.dismissViewControllerAnimated(true, completion:complete)
        })
    }
}